<?php

namespace App\Services\Http;

use App\Exceptions\NoTLoginException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Exception\TooManyRedirectsException;
use Illuminate\Support\Facades\Auth;

class GuzzleHttp
{
    private static $conn;

    protected static $method;

    protected static $url;
    
    protected static $type= '';

    protected $client;

    protected $data;
    

    protected $params;

    protected $debug = false;

    protected $auto = true;

    private function __construct()
    {
        $this->client = new Client();
    }

    public static function getInstance($method = 'get', $url,$type= ''){
        self::$method = $method;
        self::$url = $url;
        self::$type = $type;

        if(!(self::$conn instanceof self)){
            self::$conn = new self;
        }
        return self::$conn;
    }

    public function __clone(){
        trigger_error('不能够复制');
    }

    public function debug()
    {
        $this->debug = true;
        return $this;
    }

    public function auto($auto = true)
    {
        $this->auto = $auto;
        return $this;
    }

    public function send(array $data = []){
        return $this->doRequest($data);
    }

    public function get(){
        $this->data['query'] = $this->params;
        $ret = $this->client->request('GET', self::$url, $this->data);
        return $ret;
    }

    public function post(){
        $this->data['form_params'] = $this->params;
        $ret = $this->client->request('POST', self::$url, $this->data);
        return $ret;
    }

    public function put(){
        $this->data['query'] = $this->params;
        $ret = $this->client->request('PUT', self::$url, $this->data);
        return $ret;
    }

    public function delete(){
        $this->data['query'] = $this->params;
        $ret = $this->client->request('DELETE', self::$url, $this->data);
        return $ret;
    }

    /**
     * 执行发送请求
     */
    public function doRequest(array $data = [])
    {
        $this->params = $data;

        if (self::$type == 'im'){
            $config = config('im');
            $curTime = time();
            $this->data['headers']['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
            // $this->data['headers']['AppKey'] = '8ee7f3ff3ff30c26cf1dbc22857fd8de'; // 测试配置
            $this->data['headers']['AppKey'] = $config['AppKey'];// 正式配置
            $this->data['headers']['Nonce'] = $config['Nonce'];
            $this->data['headers']['CurTime'] = $curTime;
            //$this->data['headers']['CheckSum'] = sha1('b4cb8b2f5b2b' . '1' . $curTime);// 测试配置
            $this->data['headers']['CheckSum'] = sha1($config['Secret'] . $config['Nonce'] . $curTime);// 正式配置

            $this->data['verify'] = false;
        }
        //发送请求方式
        switch (self::$method) {
            case 'get':
                $ret = $this->get();
                break;
            case 'post':
                 $ret = $this->post();
                break;
            case 'put':
                $ret = $this->put();
                break;
            case 'delete':
                $ret = $this->delete();
                break;
            default:
                $ret = $this->get();
                break;
        }

        if($this->debug){
            $debug_data['http_code'] = $ret->getStatusCode();
            $debug_data['content'] = $ret->getBody()->getContents();
            print_r('<pre>');
            print_r($debug_data);
            print_r('</pre');
            exit;
        }

        $data = json_decode($ret->getBody(), 1);

        return $data;
    }

    public function doRequestBack($method, $url, array $data = [])
    {
        self::$method = $method;
        self::$url = $url;
        $this->params = $data;
        //后台添加token
        if(session('Authorization','')){
            $this->data['headers']['Authorization'] = 'Bearer  '.session('Authorization');
        }
        //前台添加token
        if(session('user_token','')){
            $this->data['headers']['Authorization'] = 'Bearer  '.session('user_token');
        }
        //发送请求方式
        switch (self::$method) {
            case 'get':
                $ret = $this->get();
                break;
            case 'post':
                $ret = $this->post();
                break;
            case 'put':
                $ret = $this->put();
                break;
            case 'delete':
                $ret = $this->delete();
                break;
            default:
                $ret = $this->get();
                break;
        }

        $data = json_decode($ret->getBody(), 1);
        $data = array_merge(['http_code' => 200], $data);

        if (in_array($data['code'], [900, 10, 11])) {
            session(['user_id' => '','user_token' => '']);
            //throw new NoTLoginException('未登录');
        }
        if($data['code'] == 0 && array_get($data,'data.token')){
            session(['Authorization' => array_get($data,'data.token')]);
        }
        if($data['code'] == 105){
            abort(404);
        }
        return $data;
    }
    
}